<?php
declare (strict_types=1);
namespace app\serviceapp;

use app\controller\api\Order;
use app\model\BaseModel;
use app\model\FenggeParam;
use app\model\Matchmaker;
use app\model\User;
use app\model\UserDetails;
use app\model\UserFavorite;
use app\model\UserOrder;
use app\model\UserOrderPlan;
use app\model\UserOrderPlanGoods;
use app\MyException;
use app\traits\ServiceTrait;
use app\util\JwtUtil;
use app\service\AuthGroupService;
use app\model\ReportDic;
use think\facade\Db;

/**
 * 私搭
 * Class OrderService
 * @package app\service
 */
class OrderService
{

    /**
     * 获取私搭列表
     */
    public static function getLists($userId)
    {
        $lists = UserOrder::alias('o')
            ->join('matchmaker m','o.shejishi_id=m.shejishi_id')
            ->where('user_id=:user_id', ['user_id' => $userId])
            ->field('order_id,o.shejishi_id as designer_id,order_no,status,nick_name,level,photo_url')
            ->select();
        if ($lists) {
            return $lists->toArray();
        }

        return [];
    }

    //购买私搭服务
    public static function buy($userId)
    {
        $oneUser = UserService::getUserById($userId);
        $cacheKey = config('cachekeys.buy_service') . ":USERID:" . $oneUser->user_id;
        if (!commitCheck($cacheKey)) throw new MyException(10013);
        if ($oneUser->sida_num == 0) {
            $oneUser->sida_num = UserOrder::INIT_SIDA_COUNT;//初次购买
        } else {
            $oneUser->sida_num += UserOrder::INIT_SIDA_COUNT;
        }

        try {
            $oneUser->allowField(['sida_num'])->save();
        } catch (\Exception $e) {
            throw new MyException(10001, $e->getMessage());
        }

        return (object)[];
    }

    //提交私搭
    public static function commit($designerId, $userId)
    {
        $oneDesigner = MatchmakerService::getMatchmakerById($designerId);
        $oneUser = UserService::getUserById($userId);
        $cacheKey = config('cachekeys.order_commit') . ":USERID:" . $oneUser->user_id;
        if (!commitCheck($cacheKey)) throw new MyException(10013);

        if ($oneUser->sida_num == 0) {
            throw new MyException(10001, '请先购买私搭服务');
        } else {
            $oneUser->sida_num -= 1;
        }

        BaseModel::beginTrans();
        try {
            $oneUser->allowField(['sida_num'])->save();
            $orderM = new UserOrder();
            $orderM->user_id = $oneUser->user_id;
            $orderM->order_no = generateOrderNo();
            $orderM->shejishi_id = $oneDesigner['shejishi_id'];
            $orderM->save();

        } catch (\Exception $e) {
            BaseModel::rollbackTrans();
            throw new MyException(10001, $e->getMessage());
        }

        BaseModel::commitTrans();
        return (object)[];

    }

    //私搭联系信息
    public static function contactInfo($userId)
    {
        $oneUser = UserService::getUserById($userId);
        //获取设计师信息
        $oneDesigner = MatchmakerService::getMatchmakerInfo();
        $designerInfo['designerId'] = $oneDesigner['shejishi_id'];
        $designerInfo['nickName'] = $oneDesigner['nick_name'];
        $designerInfo['level'] = $oneDesigner['level'];
        $designerInfo['wxQrcode'] = $oneDesigner['wx_qrcode'];
        $designerInfo['wx'] = $oneDesigner['wx'];
        $designerInfo['photoUrl'] = $oneDesigner['photo_url'];
        $designerInfo['introduce'] = $oneDesigner['introduce'];

        return ['remainCount' => $oneUser->sida_num,
            'designerInfo' => $designerInfo
        ];
    }

    //私搭状态信息
    public static function getOrderStatus($orderId)
    {
        $oneOrder = UserOrder::where('order_id =:order_id', ['order_id' => $orderId])->find();
        if (!$oneOrder)  throw new MyException(10004);

        //获取设计师信息
        $designerInfo = Matchmaker::field('nick_name nickName,level,wx,wx_qrcode wxQrcode,photo_url photoUrl,introduce')->find($oneOrder->shejishi_id);
        if (!$designerInfo)  throw new MyException(10004);

        $oneUser = UserService::getUserById($oneOrder->user_id);
        //$oneUser = User::where('user_id =:user_id', ['user_id' => $oneOrder->user_id])->find();

        return ['remainCount' => $oneUser->sida_num,
            'orderStatus' => $oneOrder->status,
            'orderCreateTime' => $oneOrder->create_time,
            'designerInfo' => $designerInfo->toArray()
        ];
    }

    public static function detail($data)
    {
        $where = ['order_id' => $data['orderId'], 'user_id' => $data['userId']];
        //$orderPlan = UserOrder::where('order_id=:order_id and user_id=:user_id', $where)->with(['plan','plan.planGoods'])->find();
        $orderPlan = UserOrder::where('order_id=:order_id and user_id=:user_id', $where)->with([
            'plan'=>function($query){
                $query->with('planGoods')->field('price','title','pict_url as pictUrl','tbk_item_url tbkItemUrl','tbk_tkl_url tbkTklUrl')->order('plan_id','desc');
            }
        ])->find();

        return $orderPlan;
    }

}
